<template>
  <RecursiveAuthorityCheckbox
    :authorities="authorityTable.authorityLevelData"
    :level="0"
  />
</template>

<script lang="ts" setup>
import { defineProps, watch, onUnmounted, defineEmits } from "vue";
import RecursiveAuthorityCheckbox from "./RecursiveAuthorityCheckbox.vue";
import { useAuthorityTable } from "../../../hooks/SystemManager/Authority/useAuthorityTable";

let parentProps = defineProps({
  roleId: String,
});

let { authorityTable, fetchAllAuthorityData, SetAuthorityToRole } =
  useAuthorityTable(1, 10);
fetchAllAuthorityData(parentProps.roleId);

watch(
  () => parentProps.roleId,
  (newId) => {
    fetchAllAuthorityData(parentProps.roleId);
  }
);

//父窗口的自定义事件
const emits = defineEmits(["updatecheckall"]);
watch(
  () => authorityTable.authorityLevelData,
  (newdata, olddata) => {
    emits("updatecheckall", isAllCheckedFun(authorityTable.authorityLevelData));
  }
);

//全选
function checkAll(checked: boolean) {
  SetAllAuthorityChecked(checked, authorityTable.authorityLevelData);
}
function SetAllAuthorityChecked(checked: boolean, authorities) {
  if (authorities != null && authorities.length > 0) {
    for (let [intdex, authority] of authorities.entries()) {
      authority.checked = checked;
      if (
        authority.childAuthorityList != null &&
        authority.childAuthorityList.length > 0
      ) {
        SetAllAuthorityChecked(checked, authority.childAuthorityList);
      }
    }
  }
}

//判断全选按钮是否要勾选
function isAllCheckedFun(authorities) {
  if (authorities != null && authorities.length > 0) {
    let allChecked = true; // 假设所有项都被选中
    for (let [index, authority] of authorities.entries()) {
      // console.log(index, authority.checked, authority.authorityName,authority);
      if (!authority.checked) {
        return false; // 如果当前项未选中，直接返回 false
      }

      if (
        authority.childAuthorityList != null &&
        authority.childAuthorityList.length > 0
      ) {
        // 递归检查子权限列表
        if (!isAllCheckedFun(authority.childAuthorityList)) {
          allChecked = false; // 如果任何一个子列表有未选中的项，则设置 allChecked 为 false
          break; // 可选：如果已经确定有未选中的项，可以提前退出循环
        }
      }
    }

    return allChecked; // 如果没有未选中的项，则返回 true
  } else {
    return false;
  }
}
defineExpose({ SetAuthorityToRole, checkAll });
</script>